package homework;

import java.util.Stack;

//力扣150题、逆波兰表达式求值（中等）
//思路：挨个取出字符串，若是数字入栈，不是就取出栈中两个数看符号运算后入栈，最后返回栈中值
public class evalRPN {
    public boolean isNum(String n){
        if (n.equals("+") || n.equals("-") || n.equals("*") || n.equals("/")){
            return false;
        }
        return true;
    }

    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            String tmp = tokens[i];
            if (isNum(tmp)) {
                stack.push(Integer.parseInt(tmp));
            } else {
                int num2 = stack.pop();
                int num1 = stack.pop();
                switch (tmp) {
                    case "+":
                        stack.push(num1 + num2);
                        break;
                    case "-":
                        stack.push(num1 - num2);
                        break;
                    case "*":
                        stack.push(num1 * num2);
                        break;
                    case "/":
                        stack.push(num1 / num2);
                        break;
                }
            }
        }
        return stack.pop();
    }
}
